$(function() {
    $("#login-btn").click(function(){
        clear();
        var username = $("#username").val();
        var password = $("#password").val();
        // 验证用户名
        if(username == ''){
            $("#username-warning").html("用户名不能为空！");
            return;
        }
        var regular = /^[a-zA-Z]{1,30}$/;
        if(!regular.exec(username)){
            $("#username-warning").html("用户名只能包含字母！");
            return;
        }

        // 验证密码
        if(password == ''){
            $("#password-warning").html("密码不能为空！");
            return;
        }
        regular = /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){5,19}$/;
        if(!regular.exec(password)){
            $("#password-warning").html("密码6-18位，以字母开头，只能包含字母数字和下划线！");
            return;
        }

        $.ajax({
            type:"post",
            url: "/work/login",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                "userName": username,
                "password": password
            }),
            success: function (result) {
                dealResult(result);
            },
            error: function (){
                $("#warning-fade").html("服务请求失败！");
                $("#myModal").modal();
            }
        });
    });

    function dealResult(result) {
        if(result.statusNum == 200){
            Cookies.set('userName', result.data.userName, {expires: 7, path: ''});
            Cookies.set('userId', result.data.userId, {expires: 7, path: ''});
            Cookies.set('role', result.data.role, {expires: 7, path: ''});
            window.location.href="index.html";
        }
        if(result.statusNum == 503){
            $("#username-warning").html(result.statusInfo);
        }
    }

    function clear() {
        $("#username-warning").html("");
        $("#password-warning").html("");
    }

});